package org.jin.samples.web;

import java.io.File;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class FileUploadController {
	
	
	@RequestMapping(value="/toUpLoad")
	public String toUpLoad(){
		return "upload/upload";
	}
	
	
	@RequestMapping(value = "/upload",method=RequestMethod.POST)
		public String upLoad(@RequestParam(value="file", required = false) MultipartFile file,
				HttpSession session,ModelMap model ,RedirectAttributes redirectAttributes){
		
		String path = session.getServletContext().getRealPath("upload");//获取项目路径
		String fileName = file.getOriginalFilename();//是得到上传时的文件名
		System.out.println(path);
		File targetFile = new File(path, fileName);
		if(!targetFile.exists()){
			targetFile.mkdirs();//mkdirs 创建此抽象路径名指定的目录，包括所有必需但不存在的父目录，  mkdir创建此抽象路径名指定的目录。
		}
		//保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//model.addAttribute("message", "上传成功");
		redirectAttributes.addFlashAttribute("message", "上传成功");
		return "redirect:/toUpLoad";
	}
}
